package cn.fastoo.web.backstage.web.controller.product;

import cn.fastoo.common.dao.product.ProductAttrDao;
import cn.fastoo.common.dao.product.ProductCategoryAttrgroupAttrDao;
import cn.fastoo.common.dao.product.ProductDao;
import cn.fastoo.common.entity.product.Product;
import cn.fastoo.common.entity.product.ProductAttr;
import cn.fastoo.common.sampleframe.dto.JsonResult;
import cn.fastoo.common.sampleframe.search.QuerySearch;
import cn.fastoo.common.sampleframe.search.Search;
import cn.fastoo.common.sampleframe.springside.Collections3;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


/**
 * Created by lowkey on 17/10/11.
 */
@Controller
@RequestMapping("/product/attr")
public class ProductAttrController {

    @Autowired
    private ProductAttrDao dao;
    @Autowired
    private ProductCategoryAttrgroupAttrDao productCategoryAttrgroupAttrDao;

    @RequestMapping
    public String index() {
        return "product/attr/index";
    }

    @RequestMapping("all")
    public String all() {
        return "product/attr";
    }




    @RequestMapping("/manager")
    @ResponseBody
    public String manager(@ModelAttribute ProductAttr newData,Long productCategoryAttrgroupId, QuerySearch querySearch, String op) {
        Search search = querySearch.getSearch();
        if(productCategoryAttrgroupId!=null){
            List<String> ids = productCategoryAttrgroupAttrDao.findProductAttrIdByProductCategoryAttrgroupId(productCategoryAttrgroupId);
            if(Collections3.isNotEmpty(ids)){
                search.addSearchFilter("NOTIN_id",ids);
            }

        }

        if(StringUtils.isNotBlank(op)){
            if("add".equals(op)){
                dao.insert(newData);
                //logger.info(loginUser, SystemLog.TYPE_AUTH_ROLE_ADD,String.format("用户角色[%s]",authRole.getRoleName()));
            }else {
                ProductAttr oldData = dao.findById(newData.getId());
                if(oldData==null){
                    return JsonResult.success("错误参数,请检查");
                }
                if("save".equals(op)){
                    newData.setVersion(oldData.getVersion());
                    dao.update(newData);
                }else if("del".equals(op)){
                    dao.delete(oldData);
                }
            }
            return JsonResult.success("操作成功");
        }
        return JsonResult.querySearchSuccess(dao.find(search),querySearch);
    }



}
